package com.letv.android.client.activity;

import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import com.ledim.activity.MainActivity;
import com.ledim.bean.ChatRoomBean;
import com.ledim.bean.ExpressionPackageBean;
import com.ledim.bean.LedimEpisodeBean;
import com.ledim.bean.base.BaseResultDataInfo;
import com.ledim.bean.base.BaseResultInfo;
import com.ledim.db.LedimDBManager;
import com.ledim.db.LedimDBUtils;
import com.ledim.fragment.CommonDialogFragment;
import com.ledim.itf.LedimDialogClickListner;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimApiServiceUtils;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.letv.android.client.LetvSDK;
import com.letv.android.client.album.controller.AlbumController;
import com.letv.android.client.album.controller.AlbumPlayAdController;
import com.letv.android.client.album.controller.AlbumRoomEmojController;
import com.letv.android.client.album.controller.AlbumRoomErrorTopController;
import com.letv.android.client.album.controller.AlbumRoomGestureController;
import com.letv.android.client.album.controller.AlbumRoomLoadController;
import com.letv.android.client.album.controller.AlbumRoomNetChangeController;
import com.letv.android.client.album.controller.AlbumRoomPlayVipTrailController;
import com.letv.android.client.album.controller.AlbumRoomRecommendController;
import com.letv.android.client.album.controller.LongWatchController;
import com.letv.android.client.constant.FragmentConstant;
import com.letv.android.client.controller.AlbumGestureObservable;
import com.letv.android.client.controller.ScreenObservable;
import com.letv.android.client.episode.PlayAlbumController;
import com.letv.android.client.episode.fragment.TabsRoomFragment;
import com.letv.android.client.fragment.AlbumBaseControllerFragment;
import com.letv.android.client.fragment.AlbumPlayFragment;
import com.letv.android.client.fragment.AlbumRoomFullControllerFragment;
import com.letv.android.client.fragment.AlbumRoomHalfControllerFragment;
import com.letv.android.client.fragment.AlbumRoomPlayFragment;
import com.letv.android.client.meditor.VideoRoomControllerMeditor;
import com.letv.android.client.utils.AlbumLaunchUtils;
import com.letv.android.client.view.AlbumPlayContainView;
import com.letv.android.young.client.R;
import com.letv.business.flow.album.AlbumFlowUtils;
import com.letv.business.flow.album.AlbumPlayFlow;
import com.letv.business.flow.album.AlbumPlayFlowObservable;
import com.letv.business.flow.album.PlayObservable;
import com.letv.business.flow.play.PlayStatisticsUtils;
import com.letv.core.bean.VideoBean;
import com.letv.core.constant.PlayConstant;
import com.letv.core.network.volley.Volley;
import com.letv.core.network.volley.VolleyRequest;
import com.letv.core.network.volley.VolleyRequestQueue.RequestFilter;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.StringUtils;
import com.letv.core.utils.UIsUtils;
import java.util.ArrayList;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 点播页
 *
 * @author zhuqiao
 */
public class AlbumPlayRoomActivity extends LetvBaseActivity {

    public static final String MFINISHSELFACTION = "mFinishSelfAction";
    public ObjectAnimator mUserIconAnimator;

    //动画时间
    private static final int USER_ANIM_DELAY = 3000;
    private static final int USER_ANIM_START = 1200;

    public int animLayoutWidth;

    /** 打开方式(用来区别播放不同的视频) **/
    public int mLaunchMode;
    /** 是否是4d视频 **/
    public boolean mIs4dVideo;

    /** 播放器fragment **/
    private AlbumRoomPlayFragment mAlbumPlayFragment;
    /** 半屏播放控制器fragment **/
    private AlbumRoomHalfControllerFragment mHalfControllerFragment;
    /** 全屏播放控制器fragment **/
    private AlbumRoomFullControllerFragment mFullControllerFragment;
    /** Tabs签fragment **/
    private TabsRoomFragment mTabsFragment;

    /** videoView和videoController交互中介者 **/
    private VideoRoomControllerMeditor mVideoControllerMeditor;

    /** 点播流程 **/
    private AlbumPlayFlow mPlayAlbumFlow;

    /** 点播流程变化观察者 **/
    private AlbumPlayFlowObservable mFlowObservable = new AlbumPlayFlowObservable();
    /** 播放过程中状态变化观察者 **/
    private PlayObservable mPlayObservable;
    /** 手势状态变化观察者 **/
    private AlbumGestureObservable mGestureObservable = new AlbumGestureObservable();
    /** 横竖屏切换观察者 **/
    private ScreenObservable mScreenObservable = new ScreenObservable();
    /** 手势控制器 **/
    private AlbumRoomGestureController mGestureController;
    /** 广告控制器 **/
    private AlbumPlayAdController mPlayAdController;
    /** vip试看工具类 **/
    private AlbumRoomPlayVipTrailController mVipTrailController;
    /** 控制工具类(返回、切换横竖屏) **/
    private AlbumController mController;
    /** 网络切换提示布局控制器 **/
    private AlbumRoomNetChangeController mNetChangeController;
    /** 覆盖videoview时，显示的返回、标题、全半屏切换控制器 **/
    private AlbumRoomErrorTopController mTopController;
    /** 推荐提示控制器 **/
    private AlbumRoomRecommendController mRecommendController;
    /** 长时间观看控制器 **/
    private LongWatchController mLongWatchController;
    /** loadlayout控制器 **/
    private AlbumRoomLoadController mLoadController;
    /** 底部tab控制器 **/
    private PlayAlbumController playAlbumController;

    public AlbumRoomEmojController emojController;
    /** 是否正在显示长时间观看 **/
    public static boolean sIsShowingLongwatch = false;
    /** 用户如果不是手动的点击暂停，那么就不要有广告的弹出 **/
    public static boolean sIsBlockPause = false;
    public static boolean sIsFromDownload = false;
    public static boolean sIsFromCollection = false;
    public static boolean sIsFromDobiChannel = false;
    public boolean mFromPushMsg;//从个推消息跳转而来

    private FrameLayout mBottomFrame, mFloatFrame;

    private boolean mHasStartFlowOnStart = false;

    private int mPlayVid = -1;

    private ChatRoomBean mRoom;
    private boolean isMe;
    private CommonDialogFragment mEnsureOutDialog;//退出确认框Dialog
    private CommonDialogFragment mCloseRoomDialog;//关闭Room确认Dialog

    private BroadcastReceiver mFinishSelf = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent intent) {
            if (intent.getAction().equals("mFinishSelfAction")) {
                finish();
            }
        }
    };
    private boolean isFromEditScreenroom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.letv_activity_play_album_room);
        LogUtil.e("ccx onCreate");
        LetvSDK.getInstance().init();
        emojController = new AlbumRoomEmojController();

        initMParams();
        AlbumLaunchUtils.setIsPidIn(getIntent());
        initDataFromIntent(getIntent());
        init();
        initFragments();

        IntentFilter mfFilter = new IntentFilter(MFINISHSELFACTION);
        registerReceiver(mFinishSelf, mfFilter);
        if (isMe) {
            View player_half_controller_stop = findViewById(R.id.player_half_controller_stop);
            player_half_controller_stop.setVisibility(View.VISIBLE);
            player_half_controller_stop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showCloseRoom();
                }
            });
        }
    }

    /**
     * 开启用户头像动画
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void startUserIconAnim() {
        if (mFullControllerFragment.ll_name_gold.getTranslationX() != 0) {
            mFullControllerFragment.ll_name_gold.setTranslationX(0);
        }
        if (mUserIconAnimator != null) {
            if (mUserIconAnimator.isStarted()) {
                mUserIconAnimator.cancel();
            }
        }
        mUserIconAnimator =
                ObjectAnimator.ofFloat(mFullControllerFragment.ll_name_gold, "translationX", 0, animLayoutWidth);
        mUserIconAnimator.setStartDelay(USER_ANIM_DELAY);
        mUserIconAnimator.setInterpolator(new AccelerateInterpolator());
        mUserIconAnimator.setDuration(USER_ANIM_START);
        mUserIconAnimator.start();
    }

    //@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    //public void cancelUserIconAnim() {
    //    if (mUserIconAnimator != null && mUserIconAnimator.isStarted()) {
    //        mUserIconAnimator.cancel();
    //    }
    //}

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent == null) {
            return;
        }
        finish();
        Intent tempIntent = new Intent(getApplicationContext(), AlbumPlayRoomActivity.class);
        if (intent.getExtras() != null) {
            tempIntent.putExtras(intent.getExtras());
        }
        tempIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplicationContext().startActivity(tempIntent);
        return;
        //initDataFromIntent(intent);
        //initWithIntent(intent);
        //initWindow();
        //if (mPlayAlbumFlow != null) {
        //    mPlayAlbumFlow.format();
        //}
        //startFlow(intent);
    }

    @Override
    protected void onStart() {
        LogUtil.e("onConfigurationChanged onstar");
        super.onStart();
        // 保证fragment都初始化完成
        if (!mHasStartFlowOnStart) {
            mHasStartFlowOnStart = true;
            startFlow(getIntent());
        }
        initWindow();
        UIsUtils.enableScreenAlwaysOn(this);
        // 统计-后台返回
        if (mPlayAlbumFlow != null && mHomeKeyEventReceiver != null &&
                mHomeKeyEventReceiver.isHomeClicked()) {
            mPlayAlbumFlow.getPlayInfo().mReplayType = 3;
            mPlayAlbumFlow.getPlayInfo().mIsAfterHomeClicked = true;
            boolean hasFinishAd =
                    (mPlayAdController != null && mPlayAdController.getAdFragment().isFinishAd());
//            mPlayAlbumFlow.statisticsLaunchAndInit(hasFinishAd);
            PlayStatisticsUtils.statisticsLaunchAndInit(getApplicationContext(),mPlayAlbumFlow,hasFinishAd);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mController.onResume();
        mGestureController.onResume();
        mController.initDefaultSensor(); // 初始化陀螺仪
        mAlbumPlayFragment.onResume();
        mAlbumPlayFragment.callAdsPlayInterface(AlbumPlayFragment.ON_ACTIVITY_RESUME, false);
        // 收集点击图片播放视频到此处所用的时间
        if (mPlayAlbumFlow != null) {
            mPlayAlbumFlow.getPlayInfo().mTimeFromClickToPlayOnResume =
                    StringUtils.staticticsLoadTimeInfoFormat(
                            System.currentTimeMillis() - StatisticsUtils.mClickImageForPlayTime);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPlayAdController.pause();
        mAlbumPlayFragment.onPause();
        mAlbumPlayFragment.callAdsPlayInterface(AlbumPlayFragment.ON_ACTIVITY_PAUSE, false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        UIsUtils.disableScreenAlwaysOn(this);
        if (mPlayAlbumFlow != null && !mPlayAlbumFlow.isAdFinished()) {
            // 上报动作22
            if (mPlayAlbumFlow.getPlayInfo().mTotalConsumeTime != 0) {
                mPlayAlbumFlow.getPlayInfo().mTotalConsumeTime =
                        mPlayAdController.getAdFragment().getAdsPlayFirstFrameTime() -
                                mPlayAlbumFlow.getPlayInfo().mTotalConsumeTime;
                PlayStatisticsUtils.staticticsLoadTimeInfo(this, mPlayAlbumFlow, mPlayAdController.getAdFragment());
            }
        }
        mPlayAdController.pause();
        mAlbumPlayFragment.pause();
        mAlbumPlayFragment.pauseCde();
        mController.onDestory();
        if (mPlayAlbumFlow != null && mAlbumPlayFragment.getPlayingHandler() != null &&
                mHomeKeyEventReceiver != null && mHomeKeyEventReceiver.isHomeClicked()) {
            mPlayAlbumFlow.getPlayInfo().mGlsbNum += 1;
            mAlbumPlayFragment.getPlayingHandler().stopHandlerTime();
            mAlbumPlayFragment.getPlayingHandler().onStopBack();
        }
    }

    /**
     * 初始化M站信息
     */
    private void initMParams() {
        StatisticsUtils.setStartType("");
        AlbumLaunchUtils.initMParams(this, getIntent());
    }

    /**
     * 确认关闭放映厅
     */
    private void showCloseRoom() {
        if (mCloseRoomDialog == null) {
            mCloseRoomDialog =
                    CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_VERCTIAL_TYPE, "是否要关闭放映厅？", "放映结束，各回各家吧", "不小心手滑了", new LedimDialogClickListner() {
                        @Override
                        public void onClickPositive(View view) {
                            modifyRoomState("0");
                        }

                        @Override
                        public void onClickNegative(View view) {

                        }

                        @Override
                        public void onDismiss() {

                        }
                    });
        }
        mCloseRoomDialog.showDialog(getSupportFragmentManager());

    }

    /**
     * @param status
     *         1 开启 0关闭
     *         开启或者关闭放映厅
     */
    private void modifyRoomState(String status) {
        LedimApiServiceUtils.modifyRoomStatus(mRoom.roomId, status, new LedimHttpObserver<BaseResultDataInfo<ChatRoomBean>>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(BaseResultDataInfo<ChatRoomBean> chatRoomBeanBaseRequestData) {
                super.onNext(chatRoomBeanBaseRequestData);
                if (chatRoomBeanBaseRequestData.success) {
                    upToHome();
                    finish();
                }
            }
        });
    }

    /**
     * 从intent中获取数据
     */
    private void initDataFromIntent(Intent intent) {
        if (intent == null || intent.getExtras() == null) {
            return;
        }
        mFromPushMsg = intent.getBooleanExtra(ConstantUtil.FROM_PUSH_MSG, false);
        if (mFromPushMsg) {
            int pushMsgCount = LedimSpUtils.getPushMgsCount();
            if (pushMsgCount > 0) {
                pushMsgCount--;
                LedimSpUtils.setPushMgsCount(pushMsgCount);
            }
        }
        //得到从LetvSDK.getInstance().play()传过来的ROOM对象
        mRoom = (ChatRoomBean) intent.getSerializableExtra(PlayConstant.ROOM);
        isMe = intent.getBooleanExtra(PlayConstant.IS_ME, false);

        isFromEditScreenroom = intent.getBooleanExtra(PlayConstant.IS_FROM_EDIT_SCREENROOM, false);
        mRoom.time = System.currentTimeMillis();
        LedimDBUtils.saveChatRoom(mRoom);
        mTabsFragment = TabsRoomFragment.getInstance(isMe, mRoom);

        mLaunchMode = intent.getIntExtra(PlayConstant.LAUNCH_MODE, 0);
        mIs4dVideo = !TextUtils.isEmpty(getIntent().getStringExtra(PlayConstant.HAPT_URL));

        if (mLaunchMode == 0) {
            String path = null;
            if (null != intent && null != intent.getData()) {
                Uri uriPath = intent.getData();
                String scheme = uriPath.getScheme();
                if (scheme == null || scheme.equals("file")) {
                    path = uriPath.getPath();
                } else {
                    path = uriPath.toString();
                }
            }
            mLaunchMode = PlayConstant.LAUNCH_MODE_URI;
            intent.putExtra(PlayConstant.LAUNCH_MODE, PlayConstant.LAUNCH_MODE_URI);
            intent.putExtra(PlayConstant.URI, path);
            intent.putExtra(PlayConstant.SEEK, 0);
            intent.putExtra(PlayConstant.PLAY_MODE, PlayConstant.PLAY_MODE_SYSTEM);
        }
    }

    private void init() {
        mTabsFragment.setActivity(this);
        mBottomFrame = getViewById(R.id.play_album_bottom_frame);
        mFloatFrame = getViewById(R.id.layout_album_float_frame);
        getViewById(R.id.play_album_full_episode).getLayoutParams().width =
                UIsUtils.dipToPx(this, 283);

        mAlbumPlayFragment = new AlbumRoomPlayFragment(this, isMe, isFromEditScreenroom);
        mHalfControllerFragment =
                new AlbumRoomHalfControllerFragment(this, getViewById(R.id.player_half_controller_contain));
        mFullControllerFragment =
                new AlbumRoomFullControllerFragment(this, getViewById(R.id.player_full_controller_contain));

        mPlayObservable = new PlayObservable(this);
        playAlbumController = new PlayAlbumController(this);

        mVideoControllerMeditor =
                new VideoRoomControllerMeditor(mHalfControllerFragment, mFullControllerFragment, mAlbumPlayFragment);
        mAlbumPlayFragment.setControllerMeditor(mVideoControllerMeditor);
        mHalfControllerFragment.setMeditor(mVideoControllerMeditor);
        mFullControllerFragment.setMeditor(mVideoControllerMeditor);

        if (mRoom != null) {
            mHalfControllerFragment.setUserInfo(mRoom);
            mFullControllerFragment.setUserInfo(mRoom);
        }

        mGestureController =
                new AlbumRoomGestureController(this, mAlbumPlayFragment, mGestureObservable);
        mPlayAdController = new AlbumPlayAdController(this);
        mVipTrailController = new AlbumRoomPlayVipTrailController(this);

        mController = new AlbumController(this);
        mController.initDefaultSensor(); // 初始化陀螺仪

        mTopController = new AlbumRoomErrorTopController(this);
        mNetChangeController = new AlbumRoomNetChangeController(this);
        mRecommendController = new AlbumRoomRecommendController(this);
        mLongWatchController = new LongWatchController(this);
        mLoadController = new AlbumRoomLoadController(this, mBottomFrame);
        mLoadController.setOnBlockCallBack(mFullControllerFragment);

        //设置直播
        mGestureController.setLive();

        AlbumPlayContainView parentView = getViewById(R.id.play_album_parent_view);
        parentView.setLongWatchController(mLongWatchController);
        getSupportFragmentManager().beginTransaction()
                                   .add(R.id.play_album_ad_contain, mPlayAdController.getAdFragment())
                                   .commitAllowingStateLoss();

        addObserverToScreenObservable();
        addObserverToFlowObservable();
        addObserverToPlayObservable();
        addObserverToGestureObservable();

        initWithIntent(getIntent());

        ViewTreeObserver viewTreeObserver =
                mHalfControllerFragment.ll_name_gold.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mHalfControllerFragment.ll_name_gold.getViewTreeObserver()
                                                    .removeGlobalOnLayoutListener(this);
                animLayoutWidth = mHalfControllerFragment.ll_name_gold.getMeasuredWidth();
            }
        });
    }

    private void initWithIntent(Intent intent) {
        if (intent == null || intent.getExtras() == null) {
            return;
        }

        mAlbumPlayFragment.setIntent(intent);

        mFullControllerFragment.setLaunchMode(mLaunchMode);
        mFullControllerFragment.setIs4d(mIs4dVideo);

        boolean isDolby = intent.getExtras().getBoolean(PlayConstant.IS_DOLBY);
        mPlayAdController.setLaunchMode(mLaunchMode, mIs4dVideo, isDolby);
        if (isDolby) {
            mTopController.setVisibilityForSwitchView(View.GONE);
        }

        if (mLaunchMode == PlayConstant.LAUNCH_MODE_VIDEO || mIs4dVideo ||
                mLaunchMode == PlayConstant.LAUNCH_MODE_URI) {
            mController.fullLock();
        }

        mFullControllerFragment.initFullState();

    }

    /**
     * 给点播流程观察者添加对象
     */
    private void addObserverToScreenObservable() {
        mScreenObservable.addObserver(mAlbumPlayFragment);
        mScreenObservable.addObserver(mHalfControllerFragment);
        mScreenObservable.addObserver(mFullControllerFragment);
        mScreenObservable.addObserver(mRecommendController);
    }

    public void setLockPortraitScreen(boolean islock) {
        if (islock) {
            UIsUtils.setScreenPortrait(this);
        }
        lockAll = islock;
    }

    public boolean lockAll;

    /**
     * 给点播流程观察者添加对象
     */
    private void addObserverToFlowObservable() {
        mFlowObservable.addObserver(mAlbumPlayFragment);
        mFlowObservable.addObserver(mHalfControllerFragment);
        mFlowObservable.addObserver(mFullControllerFragment);
        mFlowObservable.addObserver(mGestureController);
        mFlowObservable.addObserver(mNetChangeController);
        mFlowObservable.addObserver(mTopController);
    }

    /**
     * 给播放观察者添加对象
     */
    private void addObserverToPlayObservable() {
        mPlayObservable.addObserver(mAlbumPlayFragment);
        mPlayObservable.addObserver(mHalfControllerFragment);
        mPlayObservable.addObserver(mFullControllerFragment);
        //        mPlayObservable.addObserver(mTabsFragment);

        // 初始化手势控制器
        mPlayObservable.addObserver(mGestureController);
        // 网络错误控制器
        mPlayObservable.addObserver(mNetChangeController);
        // 错误时上层布局控制器
        mPlayObservable.addObserver(mTopController);
    }

    /**
     * 给手势观察者添加对象
     */
    private void addObserverToGestureObservable() {
        mGestureObservable.addObserver(mAlbumPlayFragment);
        mGestureObservable.addObserver(mHalfControllerFragment);
        mGestureObservable.addObserver(mFullControllerFragment);
        mGestureObservable.addObserver(mGestureController);
    }

    private void initFragments() {

        addFragments(mTabsFragment);
    }

    /**
     * 初始化横竖屏状态
     */
    private void initWindow() {
        boolean isLandscape = UIsUtils.isLandscape(this);
        if (isLandscape) {
            // SDK 横屏
            InputMethodManager manager =
                    (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
            UIsUtils.zoomViewFull(this, mBottomFrame);
            UIsUtils.zoomViewFull(this, mFloatFrame);
            UIsUtils.fullScreen(this);

            mFullControllerFragment.full();
            mHalfControllerFragment.isHalf(false);
            mFullControllerFragment.isFull(true);
            mTabsFragment.closeKeyBoard();

        } else {
            UIsUtils.zoomView(this, 320, 180, mBottomFrame);
            UIsUtils.zoomView(this, 320, 180, mFloatFrame);
            UIsUtils.cancelFullScreen(this);
            mFullControllerFragment.closeInputDialog();
            mFullControllerFragment.half();
            mHalfControllerFragment.isHalf(true);
            mFullControllerFragment.isFull(false);

        }
        mScreenObservable.notifyObservers(ScreenObservable.ON_CONFIG_CHANGE);
    }

    /**
     * 开始执行业务流程
     */
    public void startFlow(Intent intent) {

        setLoadStatus(true);
    }

    /**
     * 设置Vid
     *
     * @param vid
     */
    public void setVid(int vid, long time) {
        if (mPlayAlbumFlow != null) {
            mPlayAlbumFlow.format();
        }
        LetvSDK.getInstance().getmVideo().setmCurrentTime(time);

        getIntent().putExtra(PlayConstant.VID, vid);
        mPlayAlbumFlow = AlbumFlowUtils.getPlayFlow(this, mLaunchMode, getIntent().getExtras());
        if (mPlayAlbumFlow != null) {
            mPlayObservable.addObserver(mPlayAlbumFlow);
            //点播流程设置点播流程观察者对象
            mPlayAlbumFlow.setObservable(mFlowObservable);
            mPlayAlbumFlow.setLoadListener(mLoadController);
            mPlayAlbumFlow.setAdListener(mPlayAdController);
            mPlayAlbumFlow.setVideoListener(mAlbumPlayFragment);
            mPlayAlbumFlow.setAlbumPlayingListener(playAlbumController);
            mPlayAlbumFlow.start();

        }
    }

    public void setData(ArrayList<LedimEpisodeBean> data) {
        mFullControllerFragment.setEpisode(data);
    }

    // 播放上一集
    public void playerLast() {
        if (mPlayAlbumFlow != null && mPlayAlbumFlow.getPlayRecord() != null) {
            mTabsFragment.refreshLast(mPlayAlbumFlow.getPlayRecord().getVideoId());
        }
    }

    // 播放下一集
    public void finishPlayer() {
        if (mPlayAlbumFlow != null && mPlayAlbumFlow.getPlayRecord() != null) {
            mTabsFragment.refreshNext(mPlayAlbumFlow.getPlayRecord().getVideoId());
        }
    }

    // 加载时不显示播放暂停按钮
    public void setLoadStatus(boolean show) {
        mHalfControllerFragment.showLoad(show);
        mFullControllerFragment.showLoad(show);
    }

    //亮度提示框
    public void showBrightness() {
        mHalfControllerFragment.showBrightness();
        mFullControllerFragment.showBrightness();
    }

    //进度提示框
    public void showSeekProgress() {
        mHalfControllerFragment.showSeekProgress();
        mFullControllerFragment.showSeekProgress();
    }

    //声音提示框
    public void showVolume() {
        mHalfControllerFragment.showVolume();
        mFullControllerFragment.showVolume();
    }

    //隐藏提示框
    public void hideLayout() {
        mHalfControllerFragment.hideLayout();
        mFullControllerFragment.hideLayout();
    }

    public void sendMessage(String text) {
        mTabsFragment.sendRoomMsg(text);
    }

    public void sendGold(boolean isFull) {
        mTabsFragment.sendGold(isFull);
    }

    public void share(boolean showLoadingBar) {
        mTabsFragment.share(showLoadingBar);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        initWindow();// 旋转后更改页面尺寸
        super.onConfigurationChanged(newConfig);
    }

    // ---------------- 获取fragment实例 ----------------

    public AlbumRoomPlayFragment getAlbumPlayFragment() {
        return mAlbumPlayFragment;
    }

    public AlbumRoomFullControllerFragment getFullControllerFragment() {
        return mFullControllerFragment;
    }

    public AlbumRoomHalfControllerFragment getHalfControllerFragment() {
        return mHalfControllerFragment;
    }

    /**
     * 获取业务流程
     * <p>
     * 响应使用flow,每次必须通过这个方法获取
     *
     * @return
     */
    public AlbumPlayFlow getFlow() {
        if (mPlayAlbumFlow != null) {
            mPlayAlbumFlow.setSkip(false);
        }
        return mPlayAlbumFlow;
    }

    /**
     * 获取当前正在播放video
     *
     * @return
     */
    public VideoBean getPlayingVideoBean() {
        return null != mPlayAlbumFlow ? mPlayAlbumFlow.getPlayingVideo() : null;
    }

    // ---------------- 获取observable实例 ----------------

    /**
     * 获取播放观察者
     *
     * @return
     */
    public PlayObservable getPlayObservable() {
        return mPlayObservable;
    }

    /**
     * 获取手势观察者
     *
     * @return
     */
    public AlbumGestureObservable getGestureObservable() {
        return mGestureObservable;
    }

    /**
     * 获取AlbumLoadController对外暴露的接口
     *
     * @return
     */
    public AlbumRoomLoadController getLoadListener() {
        return mLoadController;
    }

    /**
     * 获取试看接口
     *
     * @return
     */
    public AlbumRoomPlayVipTrailController getVipTrailListener() {
        return mVipTrailController;
    }

    /**
     * 获取手势控制器
     *
     * @return
     */
    public AlbumRoomGestureController getGestureController() {
        return mGestureController;
    }

    /**
     * 获取控制器
     *
     * @return
     */
    public AlbumController getController() {
        return mController;
    }

    public PlayAlbumController getPlayAlbumController() {
        return playAlbumController;
    }

    public AlbumRoomNetChangeController getNetChangeController() {
        return mNetChangeController;
    }

    public AlbumRoomErrorTopController getErrorTopController() {
        return mTopController;
    }

    public AlbumRoomRecommendController getRecommendController() {
        return mRecommendController;
    }

    public LongWatchController getLongWatchController() {
        return mLongWatchController;
    }

    /**
     * 获取广告工具类
     *
     * @return
     */
    public AlbumPlayAdController getPlayAdListener() {
        return mPlayAdController;
    }

    private void clearObservables() {
        if (mScreenObservable != null) {
            mScreenObservable.deleteObservers();
        }
        if (mFlowObservable != null) {
            mFlowObservable.deleteObservers();
        }
        if (mPlayObservable != null) {
            mPlayObservable.deleteObservers();
        }
        if (mGestureObservable != null) {
            mGestureObservable.deleteObservers();
        }
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            boolean isLandscape = UIsUtils.isLandscape(this);
            if (isLandscape) {
                //增加头像动画
                //cancelUserIconAnim();
                startUserIconAnim();
                mController.half();
            } else {
                if (mPlayAlbumFlow == null) {
                    quiteWucRoom();
                    upToHome();
                    finish();
                    return true;
                } else {
                    //if (mLaunchMode == PlayConstant.LAUNCH_MODE_VIDEO || mIs4dVideo ||
                    //        mLaunchMode == PlayConstant.LAUNCH_MODE_URI) {
                    //    mController.back();
                    //    return true;
                    //} else {
                    // 其他半屏
                    mController.back();
                    upToHome();
                    return true;
                    //}
                }
            }

        }
        return false;
    }

    public void upToHome() {
        if (mFromPushMsg && MainActivity.getInstance() == null) {
            upToHome(MainActivity.class, null);
        }
    }

    public void baseFinish() {
        super.finish();
        Volley.getQueue().cancelAll(new RequestFilter() {

            @Override
            public boolean apply(VolleyRequest<?> request) {
                return request != null && !TextUtils.isEmpty(request.getTag()) &&
                        request.getTag().startsWith(AlbumPlayFlow.ALBUM_FLOW_TAG);
            }
        });
        if (TextUtils.equals("Coolpad_T2-00", LetvUtils.getModelName())) {
            format();
        }
        // overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    @Override
    public void finish() {

        boolean isFirst = LedimSpUtils.getIsFirstShowDialog();

        if (isFirst) {
            if (mEnsureOutDialog == null) {
                String hint = "出去浪的时候时间不等人哦~\n记得晒完月亮就回来";
                mEnsureOutDialog =
                        CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_VERCTIAL_TYPE, hint, "好的，朕知道了！", "", new LedimDialogClickListner() {
                            @Override
                            public void onClickPositive(View view) {
                                LedimSpUtils.setIsFirstShowDialog(false);
                                baseFinish();
                            }

                            @Override
                            public void onClickNegative(View view) {

                            }

                            @Override
                            public void onDismiss() {

                            }
                        });
            }
            mEnsureOutDialog.showDialog(getSupportFragmentManager());
        } else {
            baseFinish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (!TextUtils.equals("Coolpad_T2-00", LetvUtils.getModelName())) {
            format();
        }

        AlbumBaseControllerFragment.sShowingWhenSwitch = true;

        /** 用户如果不是手动的点击暂停，那么就不要有广告的弹出 **/
        sIsBlockPause = false;
        sIsFromDownload = false;
        sIsFromCollection = false;
        sIsFromDobiChannel = false;
        emojController.onDestroy();

    }

    private void format() {
        if (mLongWatchController != null) {
            mLongWatchController.onDestory();
        }
        if (mLoadController != null) {
            mLoadController.onDestory();
        }

        mAlbumPlayFragment.onDestroy();
        mAlbumPlayFragment.callAdsPlayInterface(AlbumPlayFragment.ON_ACTIVITY_EXIT, false);

        mFullControllerFragment.onDestroy();
        mHalfControllerFragment.onDestroy();

        mController.onDestory();

        clearObservables();
        sIsShowingLongwatch = false;
        if (mFinishSelf != null) {
            unregisterReceiver(mFinishSelf);
        }
        //退出播放，SDK需要重新初始化
        LetvSDK.getInstance().setIsInited(false);
        mGestureController.onDestroy();
    }

    @Override
    public String[] getAllFragmentTags() {
        return FragmentConstant.ALBUM_FRAGMENT_TAG_ARRAY;
    }

    @Override
    public String getActivityName() {
        return AlbumPlayRoomActivity.class.getName();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    public void sendIconMsg(ExpressionPackageBean image) {
        mTabsFragment.onClickImage(image);
    }

    public void quiteWucRoom() {
        if (mRoom != null && mRoom.cosplay != 0) {
            LedimApiServiceFactory.createService(ApiService.class).quiteWucRoom(mRoom.roomId)
                                  .observeOn(AndroidSchedulers.mainThread())
                                  .subscribeOn(Schedulers.io())
                                  .subscribe(new LedimHttpObserver<BaseResultInfo>() {
                                      @Override
                                      public void onCompleted() {
                                          super.onCompleted();
                                      }

                                      @Override
                                      public void onNext(BaseResultInfo data) {
                                          super.onNext(data);
                                          if (data != null) {
                                              if (data.success) {
                                              } else {
                                                  //失败
                                                  //ToastUtil.toast(data.message);
                                              }
                                          }

                                      }

                                      @Override
                                      public void onError(Throwable e) {
                                          super.onError(e);
                                          LogUtil.e(e.getMessage());
                                      }
                                  });
        }
    }
}
